// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")
const _ = db.command
// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const today = new Date().toLocaleDateString()

  let num = await canJu.where({
    openid: wxContext.OPENID,
    due: _.and(_.gte(new Date(today + " 00:00:00")), _.lte(new Date(today + " 23:59:59")))
  }).count()

  if (num.total >= 100) {
    return {
      code: 'fail',
      res: num.total
    }
  }


  let addData = {
    openid: wxContext.OPENID,
    parentBlockRest: event.parentBlockRest,
    parentBlockDiRest: event.parentBlockDiRest,
    progressTipsNum: event.progressTipsNum,
    totalScoreRest: event.totalScoreRest,
    level: event.level,
    canPlay: true,
    win: false,
    alreadyWheel: event.alreadyWheel,
    playInfo: [{
      openid: wxContext.OPENID,
      score: event.totalScoreRest,
      name: event.name
    }],
    playTime: new Date(),
    due: new Date()
  }
  isAdd = await canJu.add({
    data: addData,
  })
  return {
    code: 'upLoadCanJuOk',
    res: isAdd
  }
}
